const api = require('../../utils/api.js');
const { getImageUrl } = require('../../utils/imageUtils.js');

Page({
  /**
   * 页面的初始数据
   */
  data: {
    exampleId: null,
    example: null,
    chatList: [],
    total: 0,
    current: 1,
    size: 20,
    loading: false,
    hasMore: true,
    
    // 用户信息
    userInfo: {},
    // 图片资源URLs (将在onLoad中动态设置)
    defaultAvatarUrl: '',
    sendIconUrl: '',
    threeIconUrl: '',
    
    // 评论输入
    commentText: '',
    showCommentModal: false,
    sending: false,
    
    // 示例图点赞
    exampleLiked: false,
    exampleLikeCount: 577,
    
    // 聊天互动
    likingIds: [], // 正在点赞的记录ID列表
    
    // 操作菜单
    showActionMenu: false,
    saving: false
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    // 动态设置图片资源URLs
    const { getIconUrl } = require('../../utils/imageUtils.js');
    this.setData({
      defaultAvatarUrl: getImageUrl('default-avatar.png'),
      sendIconUrl: getIconUrl('send.png'),
      threeIconUrl: getIconUrl('three.png')
    });
    
    console.log('默认头像URL:', getImageUrl('default-avatar.png'));
    
    const exampleId = options.id;
    if (!exampleId) {
      wx.showToast({
        title: '参数错误',
        icon: 'error'
      });
      wx.navigateBack();
      return;
    }
    
    this.setData({ exampleId: parseInt(exampleId) });
    
    // 获取用户信息
    this.getUserInfo();
    
    this.loadExampleDetail();
  },

  /**
   * 获取用户信息
   */
  getUserInfo() {
    try {
      const userInfo = wx.getStorageSync('userInfo');
      if (userInfo) {
        this.setData({
          userInfo: userInfo
        });
      }
    } catch (error) {
      console.log('获取用户信息失败:', error);
    }
  },

  /**
   * 加载示例图详情
   */
  async loadExampleDetail() {
    const { exampleId, current, size } = this.data;
    
    this.setData({ loading: true });
    
    try {
      const response = await api.get(`/api/ai-image/examples/${exampleId}/detail?page=${current}&size=${size}`);
      
      if (response.success) {
        const { example, chatList, total } = response.data;
        
        // 预填充提示词
        this.setData({
          example: example,
          prompt: example.prompt || '',
          chatList: current === 1 ? chatList : [...this.data.chatList, ...chatList],
          total: total,
          hasMore: chatList.length === size,
          loading: false
        });
      } else {
        throw new Error(response.message || '加载失败');
      }
    } catch (error) {
      console.error('加载示例详情失败:', error);
      wx.showToast({
        title: '加载失败',
        icon: 'error'
      });
      this.setData({ loading: false });
    }
  },

  /**
   * 加载更多聊天记录
   */
  async loadMoreChat() {
    if (this.data.loading || !this.data.hasMore) return;
    
    this.setData({ 
      current: this.data.current + 1 
    });
    
    await this.loadExampleDetail();
  },

  /**
   * 下拉刷新
   */
  async onPullDownRefresh() {
    this.setData({
      chatList: [],
      current: 1,
      hasMore: true
    });
    
    await this.loadExampleDetail();
    wx.stopPullDownRefresh();
  },

  /**
   * 上拉加载更多
   */
  onReachBottom() {
    this.loadMoreChat();
  },

  /**
   * 提示词输入
   */
  onPromptInput(e) {
    this.setData({
      prompt: e.detail.value
    });
  },

  /**
   * 评论输入
   */
  onCommentInput(e) {
    this.setData({
      commentText: e.detail.value
    });
  },

  /**
   * 点赞示例图
   */
  async toggleExampleLike() {
    try {
      const response = await api.post(`/api/ai-image/examples/${this.data.exampleId}/like`);
      
      if (response.success) {
        const likeInfo = response.data;
        const liked = likeInfo.liked;
        const likeCount = likeInfo.likeCount;
        
        this.setData({
          exampleLiked: liked,
          exampleLikeCount: likeCount
        });
        
        // 如果是点赞操作，自动添加到收藏
        if (liked) {
          await this.addExampleToFavorites(this.data.exampleId);
          wx.showToast({
            title: '已点赞并收藏',
            icon: 'none',
            duration: 1500
          });
        } else {
          // 如果是取消点赞，从收藏中移除
          await this.removeExampleFromFavorites(this.data.exampleId);
          wx.showToast({
            title: '取消点赞',
            icon: 'none',
            duration: 1000
          });
        }
      }
    } catch (error) {
      console.error('点赞失败:', error);
      wx.showToast({
        title: '操作失败',
        icon: 'none'
      });
    }
  },

  /**
   * 显示评论弹窗
   */
  showCommentModal() {
    this.setData({
      showCommentModal: true
    });
  },

  /**
   * 隐藏评论弹窗
   */
  hideCommentModal() {
    this.setData({
      showCommentModal: false
    });
  },

  /**
   * 发送评论
   */
  async sendComment() {
    const { commentText, exampleId, sending } = this.data;
    
    if (!commentText.trim()) {
      wx.showToast({
        title: '请输入评论内容',
        icon: 'none'
      });
      return;
    }

    if (sending) return;

    this.setData({ sending: true });

    try {
      // 这里应该调用发送评论的API
      // const response = await api.post(`/api/ai-image/examples/${exampleId}/comment`, {
      //   content: commentText.trim()
      // });

      // 模拟发送成功
      await new Promise(resolve => setTimeout(resolve, 1000));

      // 添加评论到列表顶部（模拟数据）
      const newComment = {
        id: Date.now(),
        userNickname: this.data.userInfo.nickName || '匿名用户',
        userAvatar: this.data.userInfo.avatarUrl,
        prompt: commentText.trim(),
        imageUrl: null,
        likeCount: 0,
        liked: false,
        createTime: new Date().toISOString()
      };

      this.setData({
        chatList: [newComment, ...this.data.chatList],
        total: this.data.total + 1,
        commentText: '',
        showCommentModal: false
      });

      wx.showToast({
        title: '评论发送成功',
        icon: 'success'
      });

    } catch (error) {
      console.error('发送评论失败:', error);
      wx.showToast({
        title: '发送失败，请重试',
        icon: 'error'
      });
    } finally {
      this.setData({ sending: false });
    }
  },


  /**
   * 生成图片（跳转到专用生图页面）
   */
  generateImage() {
    console.log('点击了生成按钮');
    const { prompt, exampleId } = this.data;
    console.log('当前数据:', { prompt, exampleId });
    
    if (!prompt.trim()) {
      wx.showToast({
        title: '请输入提示词',
        icon: 'none'
      });
      return;
    }
    
    const url = `/pages/ai-generate/ai-generate?exampleId=${exampleId}&prompt=${encodeURIComponent(prompt)}`;
    console.log('跳转URL:', url);
    
    // 跳转到AI生图页面
    wx.navigateTo({
      url: url,
      success: () => {
        console.log('页面跳转成功');
      },
      fail: (error) => {
        console.error('页面跳转失败:', error);
        wx.showToast({
          title: '页面跳转失败: ' + JSON.stringify(error),
          icon: 'none',
          duration: 3000
        });
      }
    });
  },


  /**
   * 点赞/取消点赞
   */
  async toggleLike(e) {
    const chatId = e.currentTarget.dataset.id;
    const { likingIds } = this.data;
    
    // 防止重复点击
    if (likingIds.includes(chatId)) return;
    
    this.setData({
      likingIds: [...likingIds, chatId]
    });
    
    try {
      const response = await api.post(`/api/ai-image/examples/chat/${chatId}/like`);
      
      if (response.success) {
        const { liked, likeCount } = response.data;
        
        // 更新列表中的点赞状态
        const chatList = this.data.chatList.map(item => {
          if (item.id === chatId) {
            return {
              ...item,
              liked: liked,
              likeCount: likeCount
            };
          }
          return item;
        });
        
        this.setData({ chatList });
        
        // 如果是点赞操作，自动添加到收藏
        if (liked) {
          await this.addToFavorites(chatId);
        } else {
          // 如果是取消点赞，从收藏中移除
          await this.removeFromFavorites(chatId);
        }
        
        wx.showToast({
          title: liked ? '已点赞并收藏' : '取消点赞',
          icon: 'none',
          duration: 1000
        });
      }
    } catch (error) {
      console.error('点赞失败:', error);
      wx.showToast({
        title: '操作失败',
        icon: 'error'
      });
    } finally {
      // 移除loading状态
      this.setData({
        likingIds: this.data.likingIds.filter(id => id !== chatId)
      });
    }
  },

  /**
   * 添加到收藏
   */
  async addToFavorites(chatId) {
    try {
      // 获取当前聊天记录信息
      const chatItem = this.data.chatList.find(item => item.id === chatId);
      if (!chatItem) {
        console.warn('未找到聊天记录:', chatId);
        return;
      }

      // 准备收藏数据
      const favoriteData = {
        type: 'image',
        contentId: chatId.toString(),
        title: chatItem.title || chatItem.prompt || '无标题',
        content: chatItem.content || chatItem.prompt || '暂无描述',
        imageUrl: chatItem.imageUrl || '', // 保存图片URL
        contentData: JSON.stringify({
          prompt: chatItem.prompt,
          style: chatItem.style,
          likeCount: chatItem.likeCount,
          createTime: chatItem.createTime
        })
      };

      // 调用收藏接口
      const response = await api.addFavorite(
        favoriteData.type,
        favoriteData.contentId,
        favoriteData.title,
        favoriteData.content,
        favoriteData.imageUrl,
        favoriteData.contentData
      );

      if (response.success) {
        console.log('添加收藏成功:', chatId);
      } else {
        console.warn('添加收藏失败:', response.message);
      }
    } catch (error) {
      console.error('添加收藏异常:', error);
      // 不显示错误提示，避免影响用户体验
    }
  },

  /**
   * 从收藏中移除
   */
  async removeFromFavorites(chatId) {
    try {
      // 调用按内容删除收藏的接口
      const response = await api.removeFavoriteByContent('image', chatId.toString());
      
      if (response.success) {
        console.log('移除收藏成功:', chatId);
      } else {
        console.warn('移除收藏失败:', response.message);
      }
    } catch (error) {
      console.error('移除收藏异常:', error);
      // 不显示错误提示，避免影响用户体验
    }
  },

  /**
   * 查看大图
   */
  previewImage(e) {
    const url = e.currentTarget.dataset.url;
    const urls = this.data.chatList.map(item => item.imageUrl);
    
    wx.previewImage({
      current: url,
      urls: urls
    });
  },

  /**
   * 复制提示词
   */
  copyPrompt(e) {
    const prompt = e.currentTarget.dataset.prompt;
    
    wx.setClipboardData({
      data: prompt,
      success: () => {
        wx.showToast({
          title: '已复制',
          icon: 'success'
        });
      }
    });
  },

  /**
   * 使用提示词
   */
  usePrompt(e) {
    const prompt = e.currentTarget.dataset.prompt;
    
    this.setData({ prompt });
    
    wx.showToast({
      title: '已应用提示词',
      icon: 'success'
    });
  },

  /**
   * 格式化时间
   */
  formatTime(dateStr) {
    const date = new Date(dateStr);
    const now = new Date();
    const diff = now - date;
    
    const minute = 60 * 1000;
    const hour = 60 * minute;
    const day = 24 * hour;
    
    if (diff < minute) {
      return '刚刚';
    } else if (diff < hour) {
      return Math.floor(diff / minute) + '分钟前';
    } else if (diff < day) {
      return Math.floor(diff / hour) + '小时前';
    } else {
      return Math.floor(diff / day) + '天前';
    }
  },

  /**
   * 获取尺寸标签
   */
  getSizeLabel(size) {
    const option = this.data.sizeOptions.find(opt => opt.value === size);
    return option ? option.label : size;
  },

  /**
   * 添加示例图到收藏
   */
  async addExampleToFavorites(exampleId) {
    try {
      const example = this.data.example;
      const contentData = JSON.stringify({
        prompt: example.prompt,
        style: example.style,
        size: example.size
      });

      await api.addFavorite(
        'example',
        exampleId.toString(),
        example.title,
        example.prompt,
        example.imageUrl,
        contentData
      );
    } catch (error) {
      console.error('添加示例图收藏失败:', error);
    }
  },

  /**
   * 从收藏移除示例图
   */
  async removeExampleFromFavorites(exampleId) {
    try {
      await api.delete(`/api/personal/favorites/content/example/${exampleId}`);
    } catch (error) {
      console.error('移除示例图收藏失败:', error);
    }
  },

  /**
   * 显示操作菜单
   */
  showActionMenu() {
    this.setData({ showActionMenu: true });
  },

  /**
   * 隐藏操作菜单
   */
  hideActionMenu() {
    this.setData({ showActionMenu: false });
  },

  /**
   * 保存示例图到相册
   */
  async saveWorkToAlbum() {
    this.hideActionMenu();
    
    const imageUrl = this.data.example?.imageUrl;
    if (!imageUrl) {
      wx.showToast({
        title: '图片地址无效',
        icon: 'none'
      });
      return;
    }

    if (this.data.saving) return;

    try {
      this.setData({ saving: true });
      
      // 检查相册权限
      const authResult = await this.checkAlbumAuth();
      if (!authResult) {
        this.setData({ saving: false });
        return;
      }

      wx.showLoading({ title: '保存中...' });

      // 下载图片
      const downloadResult = await new Promise((resolve, reject) => {
        wx.downloadFile({
          url: imageUrl,
          success: resolve,
          fail: reject
        });
      });

      if (downloadResult.statusCode === 200) {
        // 保存到相册
        await new Promise((resolve, reject) => {
          wx.saveImageToPhotosAlbum({
            filePath: downloadResult.tempFilePath,
            success: resolve,
            fail: reject
          });
        });

        wx.showToast({
          title: '保存成功',
          icon: 'success'
        });
      } else {
        throw new Error('下载失败');
      }
    } catch (error) {
      console.error('保存图片失败:', error);
      wx.showToast({
        title: error.errMsg || '保存失败',
        icon: 'none'
      });
    } finally {
      wx.hideLoading();
      this.setData({ saving: false });
    }
  },

  /**
   * 检查相册权限
   */
  async checkAlbumAuth() {
    return new Promise((resolve) => {
      wx.getSetting({
        success: (res) => {
          if (res.authSetting['scope.writePhotosAlbum'] === false) {
            // 用户之前拒绝了权限，引导用户手动开启
            wx.showModal({
              title: '需要相册权限',
              content: '保存图片需要访问您的相册，请在设置中开启权限',
              confirmText: '去设置',
              success: (modalRes) => {
                if (modalRes.confirm) {
                  wx.openSetting({
                    success: (settingRes) => {
                      resolve(!!settingRes.authSetting['scope.writePhotosAlbum']);
                    },
                    fail: () => resolve(false)
                  });
                } else {
                  resolve(false);
                }
              }
            });
          } else if (res.authSetting['scope.writePhotosAlbum'] === undefined) {
            // 第一次请求权限
            wx.authorize({
              scope: 'scope.writePhotosAlbum',
              success: () => resolve(true),
              fail: () => {
                wx.showToast({
                  title: '需要相册权限才能保存',
                  icon: 'none'
                });
                resolve(false);
              }
            });
          } else {
            // 已经有权限
            resolve(true);
          }
        },
        fail: () => resolve(false)
      });
    });
  },

  /**
   * 分享示例图
   */
  shareWork() {
    this.hideActionMenu();
    
    const example = this.data.example;
    if (!example) return;

    wx.showActionSheet({
      itemList: ['分享给朋友', '分享到朋友圈', '复制链接'],
      success: (res) => {
        if (res.tapIndex === 0) {
          wx.showToast({
            title: '请点击右上角分享',
            icon: 'none'
          });
        } else if (res.tapIndex === 1) {
          wx.showToast({
            title: '请点击右上角分享到朋友圈',
            icon: 'none'
          });
        } else if (res.tapIndex === 2) {
          wx.setClipboardData({
            data: example.imageUrl,
            success: () => {
              wx.showToast({
                title: '链接已复制',
                icon: 'success'
              });
            }
          });
        }
      }
    });
  }
});
